<template>
  <div>
    <div class="sys-menu-index" id="menus">
      <el-container>
        <el-main>
          <div class="top-buttons">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addMenu"
              v-if="permissions.indexOf('menu_sysMenu_add') > -1"
            >添加</el-button>
            <el-tooltip effect="dark" content="刷新" placement="top-start">
              <el-button circle icon="el-icon-refresh" size="small" @click="init()"></el-button>
            </el-tooltip>
          </div>
          <el-table
            :data="menusList"
            style="width: 100%"
            row-key="id"
            border
            lazy
            size="mini"
            :load="load"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="name" label="名称" width="220" show-overflow-tooltip></el-table-column>
            <el-table-column prop="type" label="类型" align="center" width="80">
              <!-- <template slot-scope="scope">
                  <el-tag size="mini" v-if="scope.row.type == '2'">按钮</el-tag>
                  <el-tag size="mini" type="success" v-else-if="(scope.row.type == '1'&&(scope.row.children.length>0&&scope.row.children[0].type=='2') || scope.row.children.length==0) &&  scope.row.parentId==-1">顶菜单</el-tag>
                  <el-tag size="mini" type="success" v-else>菜单</el-tag>
              </template>-->
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.type == 1">系统</el-tag>
                <el-tag size="mini" type="info" v-if="scope.row.type == 2">模块</el-tag>
                <el-tag size="mini" type="warning" v-if="scope.row.type == 3">菜单</el-tag>
                <el-tag size="mini" v-if="scope.row.type == 4">操作</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="component" align="center" label="组件路径" show-overflow-tooltip></el-table-column>
            <el-table-column
              prop="permission"
              align="center"
              label="菜单权限标识"
              width="200"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="icon" align="center" label="图标" width="80">
              <template slot-scope="scope">
                <div style="text-align: center">
                  <i :class="'iconfont icon-' + scope.row.icon"></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="roleCode" align="center" label="角色码">
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="240" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  v-if="permissions.indexOf('menu_sysMenu_query') > -1"
                  @click="look(scope.row)"
                >查看</el-button>
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  @click="editMenu(scope.row)"
                  v-if="permissions.indexOf('menu_sysMenu_edit') > -1"
                >编辑</el-button>
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="del(scope.row)"
                  v-if="permissions.indexOf('menu_sysMenu_del') > -1"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <el-dialog
        customClass="dialog-form"
        :title="title"
        width="680px"
        :visible.sync="showDialog"
        @close="close"
        append-to-body="true"
        :close-on-click-modal="false"
      >
        <el-container>
          <el-main>
            <el-form ref="form" :inline="true" :model="form" label-width="80px" :rules="rules">
              <el-form-item label="名称" ref="name" prop="name">
                <el-input :disabled="isLook" placeholder="请输入菜单名称" v-model="form.name" />
              </el-form-item>
              <el-form-item label="类型" ref="type" prop="type">
                <el-select
                  :disabled="isLook"
                  v-model="form.type"
                  placeholder="请选择类型"
                  @change="changeSelet()"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.type"
                    :label="item.name"
                    :value="item.type"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="路由路径" prop="component" v-if="form.type == 3">
                <el-input :disabled="isLook" placeholder="请输入路由路径" v-model="form.component" />
              </el-form-item>
              <el-form-item label="文件夹名" prop="pathUrl" v-if="form.type == 3">
                <el-input :disabled="isLook" placeholder="请输入文件夹名" v-model="form.pathUrl" />
              </el-form-item>
              <el-form-item label="系统目录" prop="pathUrl" v-if="form.type == 1">
                <el-input :disabled="isLook" placeholder="请输入文件夹名" v-model="form.pathUrl" />
              </el-form-item>
              <el-form-item label="上级菜单" prop="parentName" v-if="form.type !== 1">
                <el-select
                  :disabled="isLook"
                  v-model="form.parentName"
                  allow-create
                  default-first-option
                  placeholder="请选择上级菜单"
                  popper-class="select-box"
                  ref="selectBox"
                >
                  <el-option>
                    <el-tree
                      class="filter-tree"
                      node-key="id"
                      :data="menusListTree"
                      :props="defaultProps"
                      ref="selectTree"
                      highlight-current
                      @node-click="handleNodeClick"
                    ></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="图标" prop="icon" v-if="form.type !== 4">
                <el-select :disabled="isLook" v-model="form.icon" placeholder="请选择图标">
                  <el-option
                    class="icon-list-box"
                    v-for="item in iconList"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                    <i :class="'iconfont icon-' + item"></i>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="权限标识" prop="permission" v-if="form.type == 4">
                <el-input :disabled="isLook" placeholder="请输入权限标识" v-model="form.permission" />
              </el-form-item>
              <el-form-item label="排序" prop="sort" v-if="form.type !== 4">
                <el-input :disabled="isLook" placeholder="请输入排序号" v-model="form.sort" />
              </el-form-item>
              <el-form-item label="子节点" prop="leaf" v-if="form.type !== 4">
                <el-radio-group v-model="form.leaf">
                  <el-radio :disabled="isLook" :label="1">是</el-radio>
                  <el-radio :disabled="isLook" :label="0">不是</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="角色" prop="sort" >
                <el-select :disabled="isLook"
                           v-model="form.roleCode"
                           multiple
                           placeholder="请数据角色">
                  <el-option v-for="item in roleCodeOption" :key="item.type" :value="item.type" :label="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer" v-show="!isLook">
          <el-button
            icon="el-icon-circle-plus-outline"
            size="small"
            @click="saveForm"
            type="primary"
          >确 定</el-button>
          <el-button icon="el-icon-circle-close" size="small" @click="close">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import sysMenuApi from "./api/sysMenu.service";

export default {
  data() {
    return {
      rules: {
        name: [
          {
            required: true,
            message: "名称不能为空！",
          },
        ],
        type: [
          {
            required: true,
            message: "类型不能为空！",
          },
        ],
        component: [
          {
            required: true,
            message: "路径不能为空！",
          },
        ],
        icon: [
          {
            required: true,
            message: "图标不能为空！",
          },
        ],
        pathUrl: [
          {
            required: true,
            message: "文件夹名称不能为空！",
          },
        ],
        permission: [
          {
            required: true,
            message: "权限标识不能为空！",
          },
          {
            pattern: /^[a-zA-Z_]{1,}$/,
            message: "只允许字母及下划线",
            trigger: "blur",
          },
        ],
        sort: [
          {
            required: true,
            message: "排序不能为空！",
          },
          {
            pattern: /^[0-9]*$/,
            message: "只允许数字",
            trigger: "blur",
          },
        ],
        leaf: [
          {
            required: true,
            message: "请选择子节点类型！",
          },
        ],
        parentName: [
          {
            required: true,
            message: "上级菜单不能为空！",
          },
        ],
      },
      permissions: JSON.parse(sessionStorage.getItem("permissions")),
      title: "",
      menusList: [],
      menusListTree: [],
      options: [
        {
          type: 1,
          name: "系统",
        },
        {
          type: 2,
          name: "模块",
        },
        {
          type: 3,
          name: "菜单",
        },
        {
          type: 4,
          name: "按钮",
        },
      ],
      showDialog: false,
      form: {
        name: "",
        type: 1,
        component: "",
        parentId: null,
        icon: "",
        sort: "",
        leaf: 1, // 0：false 不是，1：true 是
        parentName: "",
        pathUrl: "",
        permission: "",
        roleCode: []
      },
      roleCodeOption: [
        {
          type: "110",
          name: "系统管理员"
        },
        {
          type: "101",
          name: "安全保密管理员"
        },
        {
          type: "011",
          name: "安全审计员"
        },
        {
          type: "000",
          name: "普通用户"
        },
        {
          type: "999",
          name: "开发人员"
        },
      ],
      defaultProps: {
        children: "children",
        label: "name",
      },
      sysMenuId: "",
      isLook: false,
      iconList: [
        "pingtairenzheng",
        "quanxianguanli",
        "yonghuguanli",
        "jiaoseguanli",
        "jiaoyixulie",
        "zuzhijigou",
        "zidianguanli",
        "rizhiguanli",
        "RectangleCopy",
        "chanpinguanli",
        "jilu",
        "icon_huabanfuben",
        "suoping",
        "xiaoxi",
        "xia",
        "zhuti",
        "quanxianguanli1",
        "txcquanjushiwufuwu",
        "jiankongkongzhiguanli",
        "xitongguanli-moxingguanli",
        "liucheng3",
        "icon_renwu",
        "caidan1",
        "quanxianguanli-1",
        "fuwuqi",
        "daiban2",
        "lishiguiji",
        "yunying",
        "hengxiangkuozhan",
        "wendang2",
        "jiankong",
        "xitongjiankong",
        "xietonggongzuo",
        "yonghuguanli2",
        "zidianguanli1",
        "wujieshejishigongju-",
        "canshu1",
        "xietong-",
        "youxiang1",
        "gongzhonghaoyunyinggongju",
        "fensiguanli",
        "wendang1",
        "wenjianguanli1",
        "caidan",
        "liucheng2",
        "zhanghaobangding",
        "fensi",
        "shezhizaixianzixun",
        "qingchuhuancun",
        "luyouqi",
        "shujutansuoshujuzhongxinmoxingguanli",
        "xitongguanli",
        "zhanghaoguanli1",
        "yonghuguanli1",
        "caidanshezhi",
        "anzhanghaotongji",
        "shouji1",
        "navicon-zdgl",
        "erji-jiaoseguanli",
        "zhanghaoguanli",
        "rizhiguanli1",
        "guijitu",
        "wenjianguanli"
      ],
      // isType: 1
    };
  },
  watch: {
    "form.type": {
      handler(n) {
        if (n) {
          if (n == 4) {
            // 需要把排序的必选去掉
            this.$set(this.rules, "sort", [])
          } else {
            // 加上排序的必选
            this.$set(this.rules, "sort", [
              {
                required: true,
                message: "排序不能为空！"
              },
              {
                pattern: /^[0-9]*$/,
                message: "只允许数字",
                trigger: "blur"
              }
            ]);
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.init();
  },
  methods: {
    handleNodeClick(data) {
      this.form.parentId = data.id;
      this.form.parentName = data.name;
      this.$refs.selectBox.blur();
    },
    // 查看
    look(row) {
      // this.isType = row.parentId== -1 ? 3 : row.type;
      let obj = {
        name: row.name,
        type: row.type,
        component: row.component,
        parentId: row.parentId,
        icon: row.icon,
        sort: row.sort,
        leaf: row.leaf == true ? 1 : 0,
        parentName: row.name,
        id: row.id,
        pathUrl: row.path,
        permission: row.permission,
      };
      this.showDialog = true;
      this.title = "查看";
      this.isLook = true;
      this.form = obj;
    },
    // 添加
    addMenu() {
      this.showDialog = true;
      this.title = "添加";
    },
    // 编辑
    editMenu(row) {
      // this.isType = row.parentId== -1 ? 3 : row.type;
      let obj = {
        name: row.name,
        type: row.type,
        component: row.component,
        parentId: row.parentId,
        icon: row.icon,
        sort: row.sort,
        leaf: row.leaf == true ? 1 : 0,
        parentName: row.name,
        id: row.id,
        pathUrl: row.path,
        permission: row.permission,
      };
      if (row.roleCode != null){
        let roleCodeString =  row.roleCode;
        obj.roleCode= roleCodeString.split(',');
      }
      this.title = "编辑";
      this.showDialog = true;
      this.form = obj;
      console.log(row);
      if (row.type !== 1) {
        this.$nextTick(() => {
          this.$refs.selectTree.setCurrentKey(row.parentId);
          let currentObj = this.$refs.selectTree.getCurrentNode();
          this.form.parentName = currentObj.name;
        });
      }
    },

    // 保存
    saveForm() {
      let _this = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.type == 4) {
            this.form.leaf = 0;
          }
          if (this.title === "添加") {
            let obj = {
              name: this.form.name,
              type: this.form.type,
              component: this.form.component ? this.form.component : 'Layout',
              parentId: this.form.parentId ? this.form.parentId : -1,
              icon: this.form.icon,
              sort: this.form.sort,
              leaf: this.form.leaf,
              pathUrl: this.form.pathUrl,
              permission: this.form.permission,
            };
            if (this.form.roleCode != null){
              obj.roleCode= this.form.roleCode.join(",");
            }
            sysMenuApi.saveSysMenu(obj).then((res) => {
              if (res.code == 10200) {
                this.$message.success("添加成功！");
                _this.close();
                _this.init();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            let obj = {
              name: this.form.name,
              type: this.form.type,
              component: this.form.component ? this.form.component : 'Layout',
              parentId: this.form.parentId ? this.form.parentId : -1,
              icon: this.form.icon,
              sort: this.form.sort,
              leaf: this.form.leaf,
              id: this.form.id,
              pathUrl: this.form.pathUrl,
              permission: this.form.permission,
            };
            obj.roleCode = this.form.roleCode.toString()
            console.log(obj)
            sysMenuApi.updateSysMenuById(obj).then((res) => {
              if (res.code == 10200) {
                this.$message.success("修改成功！");
                _this.close();
                _this.init();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },
    // 关闭
    close() {
      let obj = {
        name: "",
        type: 1,
        component: "",
        parentId: null,
        icon: "",
        sort: "",
        leaf: 1, // 0：false 不是，1：true 是
        parentName: "",
        pathUrl: "",
        permission: "",
      };
      this.form = obj;
      this.$refs["form"].resetFields();
      this.showDialog = false;
      this.isLook = false;
      // this.isType = 1
    },
    // 删除
    del(row) {
      this.$confirm("本操作将永久删除菜单，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        sysMenuApi.deleteSysMenu([row.id]).then((res) => {
          if (res.data > 0) {
            this.$message.success("菜单删除成功！");
            this.init();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 初始化数据
    init() {
      let _this = this;
      sysMenuApi.getSysMenuPage().then((res) => {
        _this.menusList = res.data;
        let data = JSON.parse(JSON.stringify(res.data));
        _this.menusListTree = data;
      });
    },
    changeSelet() {
      console.log(this.form);
      // if (this.isType == 3) {
      //   this.form.type = 1;
      //   this.form.component = "Layout";
      //   this.form.parentId = -1;
      // } else {
      //   this.form.type = this.isType;
      //   this.form.component = "";
      //   this.form.parentId = null;
      // }
    },
  },
};
</script>
<style >
.cstomMenuWidth {
  overflow: hidden;
}
.cstomMenuWidth .el-dialog__body {
  max-height: 400px;
  overflow: auto;
}
</style>
